import axios from 'axios'
import router from '@/router/index';
import { message, messageType } from '@/utils/message'

//创建axios
const instance = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 60 * 1000,
})

// 请求拦截器
instance.interceptors.request.use(
    config => {
        // 请求携带token
        const token = localStorage.getItem("edb-authorization-token")
        if (token && !config.url.endsWith("/login")) {
            config.headers["Authorization"] = "Bearer " + token;
        }
        console.log("config-->", config);
        return config;
    },
    error => {
        return Promise.reject(error)
    }
);

// 响应拦截器
instance.interceptors.response.use(
    resp => {
        console.log("resp.data-->", resp.data);
        const data = resp.data;
        console.log(data.code);
        if (data.code === 2001) {
            // localStorage.removeItem("edb-authorization-token")
            /* if (localStorage.getItem("edb-authorization-token")) {
                return resp
            }
            if (localStorage.getItem("userToken")) {
                return resp
            } */
            message(messageType().error, data.msg)
            router.push("/login")
            return null;
        }
        if (data.code === 2002) {
            // localStorage.removeItem("edb-authorization-token")
            /* if (localStorage.getItem("edb-authorization-token")) {
                return resp
            }
            if (localStorage.getItem("userToken")) {
                return resp
            } */
            message(messageType().error, data.msg)
            router.push("/login")
            return null;
        }
        if (data.code == 2008) {
            message(messageType().error, data.msg);
            return null;
        }
        if (data.code == 2010) {
            message(messageType().error, data.msg);
            return null;
        }
        if (data.code == 500) {
            message(messageType().error, data.msg);
            return null;
        }
        if (data.code == 5001) {
            message(messageType().error, data.msg);
            return null;
        }
        if (data.code == 5002) {
            message(messageType().error, data.msg)
            return null;
        }
        if (data.code == 5005) {
            message(messageType().error, data.msg)
            return null;
        }
        if (data.code == 5006) {
            message(messageType().error, data.msg)
            return null;
        }
        return resp
    },
    error => {        
        message(messageType().error, "请求失败");
        return Promise.reject(error);
    }
);

export default instance;